/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-01-13 16:48:35
 */

import React, { createContext, useContext, useEffect, useReducer } from 'react';
import FileConstants from '../constants';
import { FilesReducer } from '../reducers/FilesReducer';

const FileContext = createContext();

const initialState = {
  dialog: {
    visible: false
  },
  listArr: [],
  metadataList: [],
  loading: false,
  total: 0,
  listQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {}
  }
};

const textArr = [
  {
    comment: 'backup edit',
    deleted: 0,
    fondCode: '1',
    fondName: '测试名称',
    id: 2
  }
];

const metadataList = [
  {
    c_name: 'id',
    e_name: 'id',
    show: true
  },
  {
    c_name: '代码',
    e_name: 'fondCode',
    show: true
  },
  {
    c_name: '名称',
    e_name: 'fondName',
    show: true
  }
];

const FileContextProvider = (props) => {
  const [state, dispatch] = useReducer(FilesReducer, initialState);

  const setListQuery = (query) => {
    dispatch({ type: FileConstants.SET_LIST_QUERY, query });
  };

  const fetchData = async (level = 3) => {
    dispatch({ type: FileConstants.LOADING });
    const res = await new Promise((resolve) => {
      return resolve({
        data: { metadataList, data: textArr }
      });
    });
    const data = await res.data;
    console.log('fetchData', data);
    dispatch({ type: FileConstants.DISPLAY_ITEMS, data, level });
  };

  useEffect(() => {
    fetchData();
  }, []);
  return (
    <FileContext.Provider value={{ ...state, setListQuery, fetchData }}>
      {props.children}
    </FileContext.Provider>
  );
};

export const useFileContext = () => {
  return useContext(FileContext);
};

export { FileContext, FileContextProvider };
